package blog

import (
	"fmt"
	kcommon "longblog/framework/tools/common"
	kinit "longblog/work/base/initialize"

	jgorm "github.com/jinzhu/gorm"
)

var ObjArticle Article

type Article struct {
	ID            int64  `gorm:"primary_key" json:"-"`
	LangType      int64  `gorm:"column:lang_type" json:"lang_type"`
	Title         string `gorm:"column:title" json:"title"`
	Content       string `gorm:"column:content" json:"content"`
	ArticleTypeId int64  `gorm:"column:article_type_id" json:"article_type_id"`
	Status        int64  `gorm:"column:status" json:"status"`
	SortNum       int64  `gorm:"column:sort_num" json:"sort_num"`
	CreatedAt     string `gorm:"column:created_at" json:"created_at"`
	UpdatedAt     string `gorm:"column:updated_at" json:"updated_at"`
}

func (Article) TableName() string {
	return "article"
}
func (ts *Article) Insert(tx *jgorm.DB, lang_type int64, title string, content string, article_type_id int64) (Article, error) {
	if tx == nil {
		tx = kinit.Gorm
	}

	tm := kcommon.TimestampToDateTime(kcommon.GetTimes())
	obj := Article{
		LangType:      lang_type,
		Title:         title,
		Content:       content,
		ArticleTypeId: article_type_id,
		Status:        1,
		SortNum:       0,
		CreatedAt:     tm,
		UpdatedAt:     tm,
	}
	if err := tx.Create(&obj).Error; err != nil {
		kinit.LogError.Println(err)
		return obj, err
	}
	return obj, nil
}

func (ts *Article) UpdateMById(tx *jgorm.DB, id int64, m map[string]interface{}) (err error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	err = tx.Model(&Article{}).Where("id=?", id).Updates(m).Error
	return
}
func (ts *Article) DeleteById(tx *jgorm.DB, id int64) (err error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	var obj Article
	err = tx.Where("id = ?", id).Delete(&obj).Error
	return
}
func (ts *Article) GetById(tx *jgorm.DB, id int64) (result Article, err error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	err = tx.Where("id = ?", id).First(&result).Error
	return
}

// 根据N个条件查询多个记录
func (ts *Article) GetAllWith(tx *jgorm.DB, title string, langType, articleTypeId int64) (result []*Article, err error) {
	if tx == nil {
		tx = kinit.Gorm
	}
	if len(title) > 0 {
		tx = tx.Where("title LIKE ?", fmt.Sprintf("%s%s%s", "%", title, "%"))
	}
	if langType > 0 {
		tx = tx.Where("lang_type = ?", langType)
	}
	if articleTypeId > 0 {
		tx = tx.Where("article_type_id = ?", articleTypeId)
	}
	err = tx.Where("status = ?", 1).Order("sort_num desc").Find(&result).Error
	return
}
